<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="iOS基础,">










<meta name="description" content="本文是 Objective-C 的快速上手文章，只要你之前有 Java 或者 C++ 的基础，相信入门 Objective-C ，只需要很短的时间。  OC 语法概览源代码文件拓展名对比    头文件 实现文件    c .h .c   c++ .h .cpp   oc .h .m   oc&amp;amp;&amp;amp;c++ .h .mm   类的定义123@interface MyClass:NSOb">
<meta name="keywords" content="iOS基础">
<meta property="og:type" content="article">
<meta property="og:title" content="Objective-C快速上手">
<meta property="og:url" content="https://zachaxy.github.io/2017/06/05/Objective-C快速上手/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="本文是 Objective-C 的快速上手文章，只要你之前有 Java 或者 C++ 的基础，相信入门 Objective-C ，只需要很短的时间。  OC 语法概览源代码文件拓展名对比    头文件 实现文件    c .h .c   c++ .h .cpp   oc .h .m   oc&amp;amp;&amp;amp;c++ .h .mm   类的定义123@interface MyClass:NSOb">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.296Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Objective-C快速上手">
<meta name="twitter:description" content="本文是 Objective-C 的快速上手文章，只要你之前有 Java 或者 C++ 的基础，相信入门 Objective-C ，只需要很短的时间。  OC 语法概览源代码文件拓展名对比    头文件 实现文件    c .h .c   c++ .h .cpp   oc .h .m   oc&amp;amp;&amp;amp;c++ .h .mm   类的定义123@interface MyClass:NSOb">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2017/06/05/Objective-C快速上手/">





  <title>Objective-C快速上手 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/06/05/Objective-C快速上手/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">Objective-C快速上手</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-05T15:28:42+08:00">
                2017-06-05
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  3,086
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <blockquote>
<p>本文是 Objective-C 的快速上手文章，只要你之前有 Java 或者 C++ 的基础，相信入门 Objective-C ，只需要很短的时间。</p>
</blockquote>
<h1 id="OC-语法概览"><a href="#OC-语法概览" class="headerlink" title="OC 语法概览"></a>OC 语法概览</h1><h2 id="源代码文件拓展名对比"><a href="#源代码文件拓展名对比" class="headerlink" title="源代码文件拓展名对比"></a>源代码文件拓展名对比</h2><table>
<thead>
<tr>
<th></th>
<th>头文件</th>
<th>实现文件</th>
</tr>
</thead>
<tbody><tr>
<td>c</td>
<td>.h</td>
<td>.c</td>
</tr>
<tr>
<td>c++</td>
<td>.h</td>
<td>.cpp</td>
</tr>
<tr>
<td>oc</td>
<td>.h</td>
<td>.m</td>
</tr>
<tr>
<td>oc&amp;&amp;c++</td>
<td>.h</td>
<td>.mm</td>
</tr>
</tbody></table>
<h2 id="类的定义"><a href="#类的定义" class="headerlink" title="类的定义"></a>类的定义</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">@interface MyClass:NSObject</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>定义一个类，以@interface MyClass:NSObject 开头，以@end 结尾，类名就是 MyClass，后面跟一个冒号，其含义就是 Java 中的 extends 关键字， 表示继承自 NSObject 类</p>
<p>遇到@符号，编译器会进行相应的预处理。</p>
<p>声明之中只有属性的定义，方法的声明，并没有方法的具体实现，具体实现是在类的实现中。从这个角度看，类的声明又很像是 Java 中的接口。类的声明一般是放在头文件中<code>.h</code>中</p>
<h2 id="属性的定义"><a href="#属性的定义" class="headerlink" title="属性的定义"></a>属性的定义</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">@interface Person:NSObject</span><br><span class="line">	@property NSString *firstName;</span><br><span class="line">	@property NSNumber *age;</span><br><span class="line">	@property int id;</span><br><span class="line">	@property (readonly)NSString * lastName;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>定义属性必须以@property 开头，然后是属性的类型，后面是变量名，如果变量是以<code>*</code>开头的，那么表明这个变量是一个指针，指向的是一块对内存中的区域；</p>
<p>同时，属性也有基本类型，eg：int，double 等，这表明的是一个基本类型；</p>
<p>用(readonly)前缀的变量，表明该变量时只读的，这和 Java 中的 final 关键字很类似</p>
<h2 id="方法的定义"><a href="#方法的定义" class="headerlink" title="方法的定义"></a>方法的定义</h2><p>减号方法（普通方法，又称为对象方法）</p>
<p>加号方法（类方法，又称为静态方法）</p>
<h2 id="类的实现"><a href="#类的实现" class="headerlink" title="类的实现"></a>类的实现</h2><p>类的声明和实现是分开的，也就是说声明之中只有属性的定义，方法的声明，并没有方法的具体实现，具体实现是在类的实现中。从这个角度看，类的声明又很像是 Java 中的接口</p>
<h2 id="完整的例子"><a href="#完整的例子" class="headerlink" title="完整的例子"></a>完整的例子</h2><p>定义类 <code>Person.h</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">@interface Person:NSObject</span><br><span class="line">-(void)sayHello;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>实现类<code>Person.m</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"># import &quot;Person.h&quot;</span><br><span class="line"></span><br><span class="line">@implementation Person</span><br><span class="line">-(void)sayHello&#123;</span><br><span class="line"> 	NSLog(@&quot;hello,world&quot;);</span><br><span class="line">&#125; </span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>在实现方法中，有一个 NSLog 的方法，这个方法是一个静态方法，类似于 Java 中的 System.out.println 方法；</p>
<p>在”hello world”字符串之前，加一个@符号，表明这是一个 OC 类型的字符串，OC 是完美支持 C 语言的，如果不加@符号，那么表明这是一个 C 语言类型的字符串（其实就是一个字符数组）。</p>
<h2 id="简单的-main-方法"><a href="#简单的-main-方法" class="headerlink" title="简单的 main 方法"></a>简单的 main 方法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">#import &lt;Foundation/Foundation.h&gt;</span><br><span class="line"></span><br><span class="line">int main(int argc, char const *argv[])</span><br><span class="line">&#123;</span><br><span class="line">	/* code */</span><br><span class="line">	@autoreleasepool&#123;</span><br><span class="line">		NSLog(@&quot;hello world&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h1><h2 id="基本数据类型"><a href="#基本数据类型" class="headerlink" title="基本数据类型"></a>基本数据类型</h2><ul>
<li>int：4byte</li>
<li>float：4byte</li>
<li>double：8byte</li>
<li>char；1byte</li>
<li>boolean ：和其它语言不一样的是，oc 中 true 是用 1 来表示的，false 是用</li>
</ul>
<p>限定词：</p>
<ul>
<li>long：long int a，表示加长版的 int，简写为：long a</li>
<li>long long：long long int a，表示加长版的 long，简写为：long long  a</li>
<li>short：short int a，表示简短版的 short，简写为： short a</li>
<li>unsigned：unsigned int a，表示无符号整形</li>
<li>signed：signed int a；表示有符号的整形</li>
</ul>
<p>字符串:并不是基础类型，但是可以平时使用很多</p>
<p>OC 字符串类型：NSString:@”hello”，在打印时使用%@</p>
<p>C 语言字符串类型：”hello”，在打印时，使用%s</p>
<h1 id="条件控制"><a href="#条件控制" class="headerlink" title="条件控制"></a>条件控制</h1><h2 id="if"><a href="#if" class="headerlink" title="if"></a>if</h2><p>关于 OC 中的布尔值，和其它语言不同，并不是 true、false，而是用 0 来表示 false，如果 if 中的条件表达式中的值不是 0，其它所有的数字，或者字符串都可以表示 true；</p>
<h2 id="goto"><a href="#goto" class="headerlink" title="goto"></a>goto</h2><p>和 C 语言的 goto 语法相同，定义一个标签，只要不是关键字都可以，后面的代码用花括号包起来，不包也可以；然后在想要跳转的地方进行 goto label 的跳转；</p>
<p>标签并不一定要定义在 goto 语句之前出现，后面也是可以的；</p>
<h1 id="循环语句"><a href="#循环语句" class="headerlink" title="循环语句"></a>循环语句</h1><p>for、while 和 C 语言完全一样</p>
<h1 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h1><p>定义：同 C 语言</p>
<p>调用：同 C 语言</p>
<h1 id="Objective-C-面向对象"><a href="#Objective-C-面向对象" class="headerlink" title="Objective-C 面向对象"></a>Objective-C 面向对象</h1><p>OOP：面向对象编程</p>
<p>OOA：面向对象分析</p>
<p>OOD：面向对象设计</p>
<h2 id="创建类和对象"><a href="#创建类和对象" class="headerlink" title="创建类和对象"></a>创建类和对象</h2><p>在 Xcode 中创建一个类，右键 new File，选择 iOS 中的 Source，选择 Cocoa Touch Class,选择继承自 NSObject，这样的话就会生成两个文件，分别是一个 .h  和 .m 文件，h 文件中写类的声明，m 中写类的实现。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">// Person.h</span><br><span class="line"># import&lt;Foundation/Foundation.h&gt;</span><br><span class="line"></span><br><span class="line">@interface Person : NSObject&#123;</span><br><span class="line">	NSString *name</span><br><span class="line">	int age;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//定义一个属性，这个属性就相当于对成员变量的 get/set</span><br><span class="line">@property(nonatomic,strong)NSString *personName;</span><br><span class="line"></span><br><span class="line">//上面属性的定义的本质就是定义了如下方法：</span><br><span class="line">/*- (void) setName:(NSString *)name;</span><br><span class="line">- (NSString *)getName;*/</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">// Person.m</span><br><span class="line">#import &quot;Person.h&quot;</span><br><span class="line"></span><br><span class="line">@implementation Person</span><br><span class="line"></span><br><span class="line">@synthesize personName = name;</span><br><span class="line"></span><br><span class="line">- (instancetype)init&#123;</span><br><span class="line">	self = [super init];</span><br><span class="line">	if (self)</span><br><span class="line">	&#123;</span><br><span class="line">		name = @&quot;张三&quot;；</span><br><span class="line">	&#125;</span><br><span class="line">	return self；</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">/*- (void) setName:(NSString *)name&#123;</span><br><span class="line">	personName = name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (NSString *)getName&#123;</span><br><span class="line">	return personName;</span><br><span class="line">&#125;*/</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>在 main 方法中使用该对象；</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">#import &lt;Foundation/Foundation.h&gt;</span><br><span class="line">#import &quot;Person.h&quot;</span><br><span class="line"></span><br><span class="line">int main(int argc, char const *argv[])</span><br><span class="line">&#123;</span><br><span class="line"> 	@autoreleasepool&#123;</span><br><span class="line">		Person *p1 = [[Person alloc]init]; </span><br><span class="line">        p1.personName = @&quot;张三&quot;;</span><br><span class="line">      	Person *p2 = [Person new];</span><br><span class="line"> 	&#125;</span><br><span class="line">	return 0;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>解析<code>Person *p1 = [[Person alloc] init];</code></p>
<p>首先，Person 是类名，后面跟变量名，但前边必须有一个 <code>*</code>,表示指针，所以在 OC 中，所有的对象都是一个指针，这其实和 Java 是类似的，因为 Java 中的对象的引用，实际上就是指向对内存中的地址，其实也就是一个指针。</p>
<ul>
<li>对于静态方法：[类名 方法名]</li>
<li>对于非静态方法：[对象名 方法名]</li>
</ul>
<p>alloc 是一个方法名，用来分配内存，init 也是一个方法名，用来初始化对象；</p>
<p>另一种初始化对象的方法是 [类名 new]，直接使用一个 new 的关键字，就代表了 alloc 和 init 两个方法，直接申请内存并初始话对象，但是这种方法与整体编码风格不搭，所以还是使用先 alloc 再 init 的方法。</p>
<h2 id="成员变量和属性"><a href="#成员变量和属性" class="headerlink" title="成员变量和属性"></a>成员变量和属性</h2><p>类内使用成员变量，类外使用属性</p>
<p>因为成员变量是只能在类内使用的，属性存在的意义是让类外访问成员变量，充当成员变量的外部访问接口。从这个角度来分析，这又有点像 Java 中的 get/set 方法；</p>
<p>所以我们在 h 文件中定义了一个属性，名字叫做 personName，那么我们直接在类外对这个属性赋值或者取值就可以了，如果没有定义属性，那么我们就必须自己手写 get/set 方法，代码量增加了。然而如何将属性和成员变量进行关联呢？</p>
<p>成员变量名：name</p>
<p>属性名：personName</p>
<p>为了建立关联，我们要在 m 文件中定义关联：<code>@synthesize personName = name;</code></p>
<p>如果成员变量名和属性名一样的话，eg 都是 name，那么关联更为简单：</p>
<p><code>@synthesize name;</code></p>
<p>但是这样写的话，带来一个困扰，就是在类中调用的究竟是成员变量还是属性，这是两个对象，这给代码的编写带来迷惑，所以不建议将属性名和成员变量名写成一样的。</p>
<p>在类内是完全没有必要调用属性的，因为成员变量在类内是完全可用的，所以我们在类内应该使用成员变量，属性是给类外使用的。</p>
<p>苹果官方推荐的做法是，成员变量使用 _name，而属性使用 name，以作区分，当然这只是一个建议，并不一定必须要这样；然后在 m 文件中使用 @synthesize 关键字进行对应，这是较老的版本的做法。</p>
<p>在新版本中则不需要这么做，如果我们想要将一个属性和成员变量进行对接，直接定义一个属性即可，也不需要再 m 文件中使用 @synthesize 关键字进行对接，SDK 已经自动帮我们生成了<code>_ 属性名</code>的成员变量，在类中我们只可以使用 _name 来获取成员变量。</p>
<p>因为成员变量是在类内才能进行调用的，所以现在成员变量在 m 文件中定义和在 h 文件中定义是没有区别的。建议在 m 文件定义吧，但是属性是一定要在 h 文件中定义的。</p>
<h2 id="方法"><a href="#方法" class="headerlink" title="方法"></a>方法</h2><h3 id="方法的声明"><a href="#方法的声明" class="headerlink" title="方法的声明"></a>方法的声明</h3><p>方法的定义是在 h 文件中，这里只有一个方法的声明，声明的形式：</p>
<p>方法类型 (方法返回值类型) 方法名 : (参数 1 类型) 参数 1 名字  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-(returnType)methodName:(typeName) variable1 :(typeName)variable2;</span><br></pre></td></tr></table></figure>

<ul>
<li>方法类型，可选的有 + 或者 -，其中前者代表类方法，后者代表对象方法</li>
<li>方法返回值类型：要用括号包裹起来，eg：(void) ，(int) ，(NSString *)等</li>
<li>方法名：和其它语言相同</li>
<li>方法参数：没有参数，那么方法名后面就不用跟冒号了，如果有参数，那么方法名后边要跟一个冒号，然后</li>
</ul>
<p>eg：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- void showName;</span><br><span class="line">- void showName : (NSString *) name;</span><br><span class="line">- void showName : (NSString *) name andAge:(int) age;</span><br></pre></td></tr></table></figure>

<h3 id="方法的实现"><a href="#方法的实现" class="headerlink" title="方法的实现"></a>方法的实现</h3><p>方法的实现是在 m 文件中；</p>
<h3 id="方法的调用"><a href="#方法的调用" class="headerlink" title="方法的调用"></a>方法的调用</h3><p>使用[ ] ，完成调用，分为两种情况：</p>
<ul>
<li>对于静态方法：[类名 方法名]</li>
<li>对于非静态方法：[对象名 方法名]</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Person p1 = [[Person alloc] init];</span><br><span class="line">[p1 showName]；</span><br><span class="line">[p1 showName: @&quot;zx&quot;]；</span><br><span class="line">[p1 showName: @&quot;zx&quot; andAge: 24]；</span><br></pre></td></tr></table></figure>

<h3 id="关于-init-方法"><a href="#关于-init-方法" class="headerlink" title="关于 init 方法"></a>关于 init 方法</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"># import&lt;Foundation/Foundation.h&gt;</span><br><span class="line"></span><br><span class="line">@interface Person : NSObject&#123;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br><span class="line">- (id) init;</span><br><span class="line">- (instancetype)init;</span><br><span class="line">- (instancetype)initPerson:(NSString *)name :(int)age;</span><br><span class="line">@end</span><br></pre></td></tr></table></figure>

<p>关于 init 方法，我们可以在类的声明中重写，其返回值类型可以是 id，表示任何类型；返回值类型可以使 instancetype，表示当前类型；单纯的初始化方法的话，其实都可以，但是要赋值的时候可能会出错，所以推荐使用后者；因为我们所有的类其实都是 NSObject 的子类，所以 init 方法不在类声明中也是可以的，如果声明的话，就相当于重写了；这里重写 init 方法的意义在于给初始化方法提供多个参数，供具体的类来使用。例如上面的 initPerson，具体实现略；</p>
<p>那么在使用时就可以用下面的方法来调用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line">Person * p1 = [[Person alloc]initPerson:@&quot;zx&quot;:20];</span><br><span class="line">...</span><br></pre></td></tr></table></figure>

<h2 id="封装"><a href="#封装" class="headerlink" title="封装"></a>封装</h2><p>屏蔽内部实现细节，只提供一个使用的接口。和 Java 无异；</p>
<h3 id="访问修饰符"><a href="#访问修饰符" class="headerlink" title="访问修饰符"></a>访问修饰符</h3><p>可用来修饰成员变量（注意不是属性）</p>
<ul>
<li>@public :在类内，类外都可以使用，并可以被继承；在类外的使用方法是：p1-&gt;name</li>
<li>@protected：默认访问修饰符，在类内可以使用，类外不可被使用，可以被继承</li>
<li>@private：只能在类内使用，不可以被继承；</li>
<li>@package：框架权限，在框架内相当于 protected，在框架外，相当于 private；</li>
</ul>
<p><strong>注：方法是没有访问修饰符</strong></p>
<p>这个用法完全和 C 语言是一样的，如果不想让人在外面使用，可以不在 h 文件中申明该方法，那么在类外就无法调用该方法了（类外引用的永远都是 h 文件，而看不到具体实现），调用直接报错；而我们可以在 m 文件中写一个方法的声明，这样的话就可以在 m 文件内部被其它方法调用了。</p>
<h2 id="继承"><a href="#继承" class="headerlink" title="继承"></a>继承</h2><p>OC 中也是单继承的，要想实现多继承的效果，可以使用协议；</p>
<p>关于继承，我们在之前其实已经见到过了，就是继承了 NSObject；NSObject 是所有类型的基类；</p>
<p>继承的语法：</p>
<ol>
<li><p>在 h 文件中</p>
<p>这时 import 的是父类的 h 文件，并且在 @interface 后面类名，后面加冒号，然后跟父类名字；</p>
</li>
<li><p>在 m 文件中，我们可以对父类中在 h 文件中声明的方法进行一个覆盖，不覆盖默认使用的是父类中的方法</p>
</li>
</ol>
<p>父类在 h 文件中声明的方法才可以被子类继承，如果没有在 h 文件中声明，那么表示只有父类自己内部可以用，外部，子类均不可用。</p>
<h2 id="多态"><a href="#多态" class="headerlink" title="多态"></a>多态</h2><p>父类引用指向子类对象；</p>
<p>OC 中不支持方法重载，只能重写</p>
<p>其它特点和 Java 无异。</p>


    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2017/06/05/Objective-C快速上手/" title="Objective-C快速上手">https://zachaxy.github.io/2017/06/05/Objective-C快速上手/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/iOS基础/" rel="tag"># iOS基础</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2017/05/28/Volley源码解析-线程切换/" rel="next" title="Volley源码解析-线程切换">
                <i class="fa fa-chevron-left"></i> Volley源码解析-线程切换
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2017/10/17/AsyncTask详解/" rel="prev" title="AsyncTask详解">
                AsyncTask详解 <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#OC-语法概览"><span class="nav-number">1.</span> <span class="nav-text">OC 语法概览</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#源代码文件拓展名对比"><span class="nav-number">1.1.</span> <span class="nav-text">源代码文件拓展名对比</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类的定义"><span class="nav-number">1.2.</span> <span class="nav-text">类的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#属性的定义"><span class="nav-number">1.3.</span> <span class="nav-text">属性的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#方法的定义"><span class="nav-number">1.4.</span> <span class="nav-text">方法的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类的实现"><span class="nav-number">1.5.</span> <span class="nav-text">类的实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#完整的例子"><span class="nav-number">1.6.</span> <span class="nav-text">完整的例子</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#简单的-main-方法"><span class="nav-number">1.7.</span> <span class="nav-text">简单的 main 方法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#变量"><span class="nav-number">2.</span> <span class="nav-text">变量</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#基本数据类型"><span class="nav-number">2.1.</span> <span class="nav-text">基本数据类型</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#条件控制"><span class="nav-number">3.</span> <span class="nav-text">条件控制</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#if"><span class="nav-number">3.1.</span> <span class="nav-text">if</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#goto"><span class="nav-number">3.2.</span> <span class="nav-text">goto</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#循环语句"><span class="nav-number">4.</span> <span class="nav-text">循环语句</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#函数"><span class="nav-number">5.</span> <span class="nav-text">函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Objective-C-面向对象"><span class="nav-number">6.</span> <span class="nav-text">Objective-C 面向对象</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建类和对象"><span class="nav-number">6.1.</span> <span class="nav-text">创建类和对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#成员变量和属性"><span class="nav-number">6.2.</span> <span class="nav-text">成员变量和属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#方法"><span class="nav-number">6.3.</span> <span class="nav-text">方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#方法的声明"><span class="nav-number">6.3.1.</span> <span class="nav-text">方法的声明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法的实现"><span class="nav-number">6.3.2.</span> <span class="nav-text">方法的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法的调用"><span class="nav-number">6.3.3.</span> <span class="nav-text">方法的调用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#关于-init-方法"><span class="nav-number">6.3.4.</span> <span class="nav-text">关于 init 方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#封装"><span class="nav-number">6.4.</span> <span class="nav-text">封装</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#访问修饰符"><span class="nav-number">6.4.1.</span> <span class="nav-text">访问修饰符</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#继承"><span class="nav-number">6.5.</span> <span class="nav-text">继承</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多态"><span class="nav-number">6.6.</span> <span class="nav-text">多态</span></a></li></ol></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
